package com.eschool.beans;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import com.eschool.beans.converter.SchoolConverter;
import com.eschool.model.School;
import com.eschool.service.CustomerService;
import com.eschool.service.impl.CustomerServiceImpl;

@ManagedBean(name = "rechargeCustomerBean")
@ViewScoped
public class RechargeCustomerBean {

	private School selectedSchool;
	private List<School> allSchools;

	private SchoolConverter schoolConverter;

	CustomerService service = new CustomerServiceImpl();

	public RechargeCustomerBean() {
		// TODO Auto-generated constructor stub
		selectedSchool = new School();
		schoolConverter = new SchoolConverter();
		allSchools = SchoolConverter.schoolDB;
	}

	public School getSelectedSchool() {
		return selectedSchool;
	}

	public void setSelectedSchool(School school) {
		this.selectedSchool = school;

	}

	public SchoolConverter getSchoolConverter() {
		return schoolConverter;
	}

	public void setSchoolConverter(SchoolConverter schoolConverter) {
		this.schoolConverter = schoolConverter;
	}

	public List<School> completeSchool(String query) {
		List<School> suggestions = new ArrayList<School>();

		for (School s : allSchools) {
			if (s.getSchoolName().toLowerCase().startsWith(query.toLowerCase()))
				suggestions.add(s);
		}

		return suggestions;
	}

	public String action() {

		String message = "";

		if (service.rechargeCustomer(selectedSchool)) {
			message = "Expiry date of " + selectedSchool.getSchoolName()
					+ " updated to "
					+ selectedSchool.getExpiryDate().toString();
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage(FacesMessage.SEVERITY_INFO, "Info Message", message));
		}
		else {
			message = "Unable to Update Expiry Date";
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error Message", message));
		}

		return "RechargeCustomer";
	}

}
